import { get } from "http";
import { Connection } from "./db/connection";
import { connectionManger } from "./db/connectionmanager";
import { mysqlTransaction } from "./db/mysqltransaction";

export async function getConnection(): Promise<any> {
    return await connectionManger.createConnection()
}




/**
 * 在事务开启，事务提交和事务回滚时，先判断事务计数属性值，
 * 当事务计数属性值为1时，才进行实际事务操作
 * 嵌套的内层里面实际没有实际的事务的，只有最外层一个整体的事务的实际的事务
 */
export async function beginTransction() {
    let conn = await getConnection()
    let tx: mysqlTransaction = connectionManger.getTransaction(conn)
    tx.beginTimes++
    if (tx.beginTimes === 1) {
        await tx.begin()
    }
}

export async function commitTransaciton() {
    let conn = await getConnection()
    let tx: mysqlTransaction = connectionManger.getTransaction(conn)
    if (tx.beginTimes === 1) {
        await tx.commit()
        connectionManger.deleteTransaction()
    }
    tx.beginTimes--
}

export async function rollbackTransaction() {
    let conn = await getConnection()
    let tx: mysqlTransaction = connectionManger.getTransaction(conn)
    if (tx.beginTimes === 1) {
        tx.beginTimes = 0
        tx.rollback()
        connectionManger.deleteTransaction()
    } else {
        tx.beginTimes--
    }
}

export async function closeConnection() {
    return connectionManger.release()
}









